package com.zhiche.lisa.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class UaaUtil {

    @Value("${uaa.getTentUrl}")
    private String getTentUrl;
    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;
    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;
    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;
    @Value("${lisa.socketTimeout}")
    private int socketTimeout;

    /**
     * 得到租户应用管理员
     */
    public List<String> getToken() {
        List<String> techAccountIdentifiers = Lists.newArrayList();
        String strReturn = HttpClientUtil.get(getTentUrl, null, 10000);
        JSONObject jsonObject = JSON.parseObject(strReturn);
        int status = jsonObject.getInteger("code");
        if (status == 0) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            if (CollectionUtils.isNotEmpty(jsonArray)) {
                jsonArray.forEach(object1 -> {
                    JSONObject jsonObject1 = (JSONObject) object1;
                    String techAccountIdentifier = jsonObject1.getString("techAccountIdentifier");
                    techAccountIdentifiers.add(techAccountIdentifier);
                });
            }
        }
        return techAccountIdentifiers;
    }


    /**
     * 获取中联1Ltoken
     */
    public String getTenantToken(String techAccountIdentifier) {
        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("username", techAccountIdentifier);
        parmers.put("password", "123456");
        parmers.put("client_id", getClinetId);
        parmers.put("client_secret", getClientSecret);
        parmers.put("grant_type", "password");
        String result = HttpClientUtil.post(getTokenUrl, parmers, socketTimeout);
        if (StringUtils.isEmpty(result)) return null;
        JSONObject jsonObject2 = JSON.parseObject(result);
        if (Objects.nonNull(jsonObject2)) {
            String access_token = jsonObject2.getString("access_token");
            return "Bearer " + access_token;
        } else {
            return null;
        }
    }
}
